import wx
import copy
import os
from decimal import Decimal as Dec

from DataTool import DataTool
from Table4rate import Table4rate
from DiaTable4ChangeRate import DiaTable4ChangeRate


class DiaTable4ChangeRates(wx.Dialog):
    material_type = ['光缆', '电缆', '塑料', '木材', '水泥', '其他', '设备', '设备(不安装)']
    collist = ['%s小计', '%s运杂费：费率%.2f%%', '%s运输保险费：小计*%.2f%%', 
                   '%s采购保管费：小计*%.2f%%', '%s采购代理服务费(直接金额)', '%s合计']
    colnamelist = ['运杂费费率', '运输保险费费率', '采购保管费费率', '采购代理服务费(直接金额)']
    books = {
            'book1': '电源设备分册',
            'book2': '有线设备分册',
            'book3': '无线设备分册',
            'book4': '线路工程分册',
            'book5': '管道工程分册',
            }
    
    ListCtrlNames = ['序号', '材料名称', '运杂费费率', '运输保险费费率', '采购保管费费率', '采购代理服务费(除税价)', '采购代理服务费(税金)']
    ListCtrlWidths = [60, 60, 100, 100, 100, 150, 150]
    BtnNames = ['修改...', '确定', '取消']
    namelist = ['运杂费', '运保费', '采购及保管费']
    SingleData = {'运杂费费率':0, '运输保险费费率':0, '采购保管费费率':0, '采购代理服务费(直接金额)':0, '税金':0}
    Fun = ['self.OnChangeRate', 'self.OnSave', 'self.OnCancel']

    def __init__(self, parent, title, *args, **kwargs):
        self.data = kwargs.get('data', list())
        self.ret = dict()
        self.path = kwargs.get('path')
        self.path = os.path.join(self.path, 'db/rate.db')
        super().__init__(parent, -1, title)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        datasizer = wx.BoxSizer(wx.VERTICAL)
        upsizer = wx.BoxSizer(wx.HORIZONTAL)
        btnsizer = wx.BoxSizer(wx.HORIZONTAL)

        self.InitUI(datasizer)
        self.InitUpUI(upsizer)
        self.InitBtn(btnsizer)

        mainsizer.Add(upsizer, 0, flag=wx.ALL|wx.EXPAND, border=0)
        mainsizer.Add(datasizer, 0, flag=wx.ALL|wx.EXPAND, border=0)
        mainsizer.Add(btnsizer, 0, flag=wx.ALL|wx.ALIGN_RIGHT, border=0)

        self.InitListCtrl()
        self.InitStandardData()

        self.SetSizer(mainsizer)
        mainsizer.Fit(self)
        mainsizer.SetSizeHints(self)
    
    def InitUI(self, sizer):
        listctrl = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.LC_SINGLE_SEL, size=(750, 300), name='ratebook')
        sizer.Add(listctrl, flag=wx.EXPAND|wx.ALL, border=5)
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectRateBook, listctrl)

    def InitUpUI(self, sizer):
        books = list(self.books.values())
        choices = books
        Choicer = wx.Choice(self, -1, choices=choices, name='bookchoicer')
        Choicer.Select(0)
        sizer.Add(Choicer, 0, flag=wx.EXPAND|wx.ALL, border=5)
        BtnOverWrite = wx.Button(self, -1, '覆盖费率')
        BtnOverWriteAll = wx.Button(self, -1, '覆盖全部费率')
        sizer.Add((30, -1), 1,flag=wx.EXPAND|wx.ALL, border=5)
        sizer.Add(BtnOverWrite, 0, flag=wx.EXPAND|wx.ALL, border=5)
        sizer.Add(BtnOverWriteAll, 0, flag=wx.EXPAND|wx.ALL, border=5)
        self.Bind(wx.EVT_BUTTON, self.OnOverWrite, BtnOverWrite)
        self.Bind(wx.EVT_BUTTON, self.OnOverWriteAll, BtnOverWriteAll)

    def InitBtn(self, sizer):
        for index, name in enumerate(self.BtnNames):
            btn = wx.Button(self, -1, label=name, name=name+'btn')
            self.Bind(wx.EVT_BUTTON, eval(self.Fun[index]), btn)
            # self.Bind(wx.EVT_BUTTON, self.OnCopy, btn)
            sizer.Add(btn, 0, flag=wx.ALL|wx.EXPAND, border=5)

    def InitListCtrl(self):
        listctrl = self.FindWindowByName('ratebook')
        for index, name in enumerate(self.ListCtrlNames):
            listctrl.InsertColumn(index, name)
            listctrl.SetColumnWidth(index, self.ListCtrlWidths[index])
        self.Refresh()

    def InitStandardData(self):
        self.Sdata = {}
        for name in self.books:
            Rate = Table4rate(name, path=self.path)
            data = Rate.getrate()
            self.Sdata[self.books[name]] = data
        for key in self.Sdata:
            for key2 in self.Sdata[key]:
                self.Sdata[key][key2] = Dec(str(self.Sdata[key][key2])) / Dec('100')

    def Refresh(self):
        listctrl = self.FindWindowByName('ratebook')
        listctrl.DeleteAllItems()
        for row, rowv in enumerate(self.data):
            index = listctrl.InsertItem(row, str(row+1))
            listctrl.SetItem(index, 1, rowv)
            for col, value in enumerate(self.data[rowv]):
                if not isinstance(self.data[rowv][value], tuple):
                    listctrl.SetItem(index, col+2, str(self.data[rowv][value]))
                else:
                    for col2, value2 in enumerate(self.data[rowv][value]):
                        listctrl.SetItem(index, col+2+col2, str(value2))

    def OnSelectRateBook(self, event):
        self.RateBookIndex = event.GetIndex()

    def OnOverWrite(self, event, num=''):
        if hasattr(self, 'RateBookIndex') or num != '':
            choicer = self.FindWindowByName('bookchoicer')
            string = choicer.GetString(choicer.GetSelection())
            rate = self.Sdata[string]
            if num == '':
                num = self.RateBookIndex
            for i, mtype in enumerate(self.data):
                for index, name in enumerate(self.data[mtype]):
                    if i == num:
                        if index <= 2:
                            chancename = mtype + self.namelist[index]
                            self.data[mtype][name] = rate[chancename]
            self.Refresh()
        else:
            dia = wx.MessageDialog(self, '请先选中一行数据！',
                    caption='警告',style=wx.OK|wx.ICON_WARNING)
            dia.ShowModal()
            dia.Destroy()
    
    def OnOverWriteAll(self, event):
        listctrl = self.FindWindowByName('ratebook')
        num = listctrl.GetItemCount()
        for i in range(num):
            self.OnOverWrite(0, i)

    def OnChangeRate(self, event):
        if hasattr(self, 'RateBookIndex'):
            keys = list(self.data.keys())
            thisdata = list(self.data.values())[self.RateBookIndex]
            thisdata = list(thisdata.values())
            for index, name in enumerate(self.SingleData):
                if index < 3:
                    self.SingleData[name] = thisdata[index]
                else:
                    self.SingleData[name] = thisdata[3][index-3]
            dia = DiaTable4ChangeRate(self, '修改费率', data=self.SingleData)
            retdata = dia.ShowModal()
            dia.Destroy()
            if retdata != 5101:
                for index, name in enumerate(retdata):
                    if index < 3:
                        self.data[keys[self.RateBookIndex]][name[:-2]] = retdata[name]
                tup = (retdata['采购代理服务费(直接金额)'], retdata['税金'])
                self.data[keys[self.RateBookIndex]]['采购代理服务费(直接金额)'] = tup
            self.Refresh()
        else:
            dia = wx.MessageDialog(self, '请先选中一行数据！',
                    caption='警告',style=wx.OK|wx.ICON_WARNING)
            dia.ShowModal()
            dia.Destroy()

    def OnSave(self, event):
        self.EndModal(retCode=1)
    
    def OnCancel(self, event):
        self.EndModal(retCode=5101)

    def ShowModal(self):
        ret = super().ShowModal()
        if ret == 5101:
            return ret
        elif ret == 1:
            return self.data
        else:
            return 5101






if __name__ == "__main__":
    import os
    from decimal import Decimal
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    class MyFrame(wx.Frame):
        def __init__(self):
            super().__init__(None, -1, 'haha', size=(200, 100))
            btn = wx.Button(self, -1, 'baba', size=(10, 10))
            self.Bind(wx.EVT_BUTTON, self.OnClick, btn)

        def OnClick(self, event):
            data = {'设备': {'运杂费': Decimal('0.008'), '运输保险费': Decimal('0.001'), '采购保管费': Decimal('0.0082'), '采购代理服务费(直接金额)': (0, 0)},
                    '电缆':{'运杂费': Decimal('0.01'), '运输保险费': Decimal('0.001'), '采购保管费': Decimal('0.01'), '采购代理服务费(直接金额)': (0, 0)}, 
                    '塑料': {'运杂费': Decimal('0.043'), '运输保险费': Decimal('0.001'), '采购保管费': Decimal('0.01'), '采购代理服务费(直接金额)': (0, 0)}, 
                    '其他': {'运杂费': Decimal('0.036'), '运输保险费': Decimal('0.001'), '采购保管费': Decimal('0.01'), '采购代理服务费(直接金额)': (0, 0)}}
            dia = DiaTable4ChangeRates(self, 'haha', name='haha', data=data, path=BASE_DIR)
            modal = dia.ShowModal()
            print(modal)
            dia.Destroy()

    app = wx.App()
    MyFrame().Show()
    app.MainLoop()